package com.joshua.ticket.manager.controllers;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.joshua.ticket.utils.LoingedUser;
import com.joshua.userservice.models.Role;
import com.joshua.userservice.models.User;
import com.joshua.userservice.models.Menu;

@Controller
@RequestMapping("")
public class LoginController {

	@Autowired
	public SessionFactory sessionFactory;

	@RequestMapping("loginPage")
	public ModelAndView getLoginPage() {
		return new ModelAndView("LoginPage");
	}

	@RequestMapping("login")
	public ModelAndView login(User user, HttpServletRequest request) {

		ModelAndView mav = null;

		String userName = user.getUsername();
		String password = user.getPassword();

		Session session = sessionFactory.openSession();
		Transaction transcation = session.beginTransaction();
		List users = session.createCriteria(User.class)
				.add(Restrictions.eq("loginName", userName))
				.add(Restrictions.eq("password", password)).list();

		if (users.size() == 1) {

			User queryUser = (User) users.get(0);

			LoingedUser loginedUser = new LoingedUser();
			loginedUser.setUserId(queryUser.getId());
			loginedUser.setUserName(queryUser.getLoginName());

			Set<Role> roles = queryUser.getRoles();
			Set<Menu> menus = new HashSet<Menu>();

			for (Role role : roles) {
				menus.addAll(role.getMenus());
				loginedUser.getRoleCodes().add(role.getRoleCode());
			}

			for (Menu menu : menus) {
				loginedUser.getMenuCodes().add(menu.getCode());
			}

			HttpSession httpSession = request.getSession();
			httpSession.setAttribute("LOGIN_USER", loginedUser);
			mav = new ModelAndView("redirect:/continent/index.do");
		} else {
			mav = new ModelAndView("redirect:/loginPage.do");
		}

		transcation.commit();
		session.close();
		
		return mav;
	}

}
